package com.enation.app.shop.front.policyInsurance.webController;


import com.enation.app.base.core.upload.IUploader;
import com.enation.app.base.core.upload.UploadFacatory;
import com.enation.app.shop.component.spec.service.ISpecManager;
import com.enation.app.shop.core.goods.model.Cat;
import com.enation.app.shop.core.goods.model.Goods;
import com.enation.app.shop.core.goods.model.GoodsType;
import com.enation.app.shop.core.goods.model.SpecValue;
import com.enation.app.shop.core.goods.plugin.GoodsPluginBundle;
import com.enation.app.shop.core.goods.service.IGoodsCatManager;
import com.enation.app.shop.core.goods.service.IGoodsManager;
import com.enation.app.shop.core.goods.service.IGoodsTypeManager;
import com.enation.app.shop.front.api.utils.ImgResponseUtil;
import com.enation.app.shop.front.policyInsurance.entity.Supplier;
import com.enation.app.shop.front.policyInsurance.entity.SysArea;
import com.enation.app.shop.front.policyInsurance.service.ISupplierMapper;
import com.enation.app.shop.front.policyInsurance.service.ISysAreaMapper;
import com.enation.app.shop.front.policyInsurance.service.InpolicyMapper;
import com.enation.app.shop.front.policyInsurance.service.JAreaManageMapper;
import com.enation.eop.SystemSetting;
import com.enation.eop.sdk.context.EopSetting;
import com.enation.eop.sdk.utils.StaticResourcesUtil;
import com.enation.framework.action.GridController;
import com.enation.framework.action.GridJsonResult;
import com.enation.framework.action.JsonResult;
import com.enation.framework.database.Page;
import com.enation.framework.util.DateUtil;
import com.enation.framework.util.FileUtil;
import com.enation.framework.util.JsonResultUtil;
import com.enation.framework.util.StringUtil;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * web端保险管理
 */
@Scope("prototype")
@Controller
@RequestMapping("web/InsuranceManage")
public class InsuranceController extends GridController {
    @Autowired
    private InpolicyMapper inpolicyMapper;

    @Autowired
    private IGoodsCatManager goodsCatManager;

    @Autowired
    private IGoodsTypeManager iGoodsTypeManager;

    @Autowired
    private GoodsPluginBundle goodsPluginBundle;

    @Autowired
    private ISupplierMapper iSupplierMapper;

    @Autowired
    private ISpecManager iSpecManager;

    @Autowired
    private JAreaManageMapper jAreaManageMapper;

    @Autowired
    private ISysAreaMapper sysAreaMapper;

    @Autowired
    private IGoodsManager iGoodsManager;

    /**
     * 获取全部保险
     *
     * @param supplier_id
     * @param cat_id
     * @param province_id
     * @param city_id
     * @param region_id
     * @param name
     * @param item
     * @return
     */
    @RequestMapping("/getAllInspolicy")
    public GridJsonResult getAllInspolicy(
            @RequestParam(value = "supplier_id", required = false) Integer supplier_id,
            @RequestParam(value = "cat_id", required = false) Integer cat_id,
            @RequestParam(value = "province_id", required = false) Integer province_id,
            @RequestParam(value = "city_id", required = false) Integer city_id,
            @RequestParam(value = "region_id", required = false) Integer region_id,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "item", required = false) String item) {
        Map inPolicyMap = new HashMap();
        Page page = new Page();
        inPolicyMap.put("supplier_id", supplier_id);
        inPolicyMap.put("cat_id", cat_id);
        inPolicyMap.put("province_id", province_id);
        inPolicyMap.put("city_id", city_id);
        inPolicyMap.put("region_id", region_id);
        inPolicyMap.put("name", name);
        inPolicyMap.put("item", item);
        List<Supplier> supplierList = iSupplierMapper.getAll();
        List<Cat> catList = goodsCatManager.listChildren(244);
        return JsonResultUtil.getGridJson(inpolicyMapper.getAllInspolicy(inPolicyMap, this.getPage(), this.getPageSize(), this.getSort(), this.getOrder()));
    }


    /**
     * 跳转添加页面
     *
     * @return
     */
    @RequestMapping("/gotoAddGoods")
    public ModelAndView GotoAddGoods() {
        ModelAndView model = new ModelAndView("/shop/admin/appinsurance/addinspolicy");
        try {

            List<GoodsType> goodsTypeList = iGoodsTypeManager.getAllGoodsType();
            List<Cat> catList = inpolicyMapper.getInPolicyCat();
            List<Supplier> supplierList = iSupplierMapper.getAll();
            List<SysArea> sysAreaList = jAreaManageMapper.getProvince();
            List<SpecValue> specList = iSpecManager.getInPolicySpecValueInfo();
//            List<Goods> goodsList = iGoodsManager.getAllInPolicyName();


//            model.addObject("goodsList", goodsList);
//            model.addObject("speciList", specList);//规格值列表
//            model.addObject("goodsTypeList", goodsTypeList);//商品分类列表
            model.addObject("sysAreaList", sysAreaList);
            model.addObject("supplierList", supplierList);//供应商列表
            model.addObject("catList", catList);//商品类型列表
            model.addObject("pluginTabs", this.goodsPluginBundle.onFillAddInputData());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return model;
    }

    /**
     * 添加保险
     *
     * @return
     */
    @RequestMapping("/addGoods")
    public JsonResult addInspolicy(HttpServletRequest request,Goods goods) {
        String province_area_code = request.getParameter("province_area_code");
        String city_area_code = request.getParameter("city_area_code");
        String region_area_code = request.getParameter("region_area_code");
        String name = goods.getName();
        if (name == null || name.trim().length() == 0) {
            return JsonResultUtil.getErrorJson("保险名称不能为空!");
        }
        //添加保险区域
        SysArea sysArea = sysAreaMapper.getByAreaCode(province_area_code);
        goods.setProvince_id(sysArea.getProvince_id());
        goods.setProvince(sysArea.getArea_name());

        SysArea sysAreaCity = sysAreaMapper.getByAreaCode(city_area_code);
        goods.setCity_id(sysAreaCity.getCity_id());
        goods.setCity(sysAreaCity.getArea_name());

        SysArea sysAreaRegion = sysAreaMapper.getByAreaCode(region_area_code);
        goods.setRegion_id(sysAreaRegion.getRegion_id());
        goods.setRegion(sysAreaRegion.getArea_name());
        goods.setArea_code(region_area_code);
        try {
            iGoodsManager.add(goods);
        } catch (Exception e) {
            this.logger.error("添加商品出错");
            return JsonResultUtil.getErrorJson("添加商品出错!");
        }
        return  JsonResultUtil.getSuccessJson("添加成功!");
    }
    /**
     * 更新保险信息
     *
     * @param request
     * @return
     */
    @RequestMapping("/updateInspolicy")
    public JsonResult updateInspolicy(HttpServletRequest request) {
        String ds = request.getParameter("policyInfo");
        JSONObject jsonObject = JSONObject.fromObject(ds);
        System.out.println(jsonObject.toString());
        Goods goods = new Goods();
        //商品添加
        String name = jsonObject.get("name").toString();
        if (name == null || name.trim().length() == 0) {
            return JsonResultUtil.getErrorJson("保险名称不能为空!");
        }
        goods.setName(name);
        goods.setType_id(jsonObject.getInt("type_id"));
//          BigDecimal bigDecimal = new BigDecimal(jsonObject.get("price").toString());
        Double price = Double.valueOf(jsonObject.get("price").toString());
        goods.setPrice(price);
        goods.setCat_id(jsonObject.getInt("cat_id"));
        goods.setSn(jsonObject.get("sn").toString());
        goods.setBrief(jsonObject.get("brief").toString());
        goods.setPoint(jsonObject.getInt("point"));
        goods.setMarket_enable(jsonObject.getInt("market_enable"));
        goods.setUnit(jsonObject.get("unit").toString());
        goods.setItem(jsonObject.get("item").toString());
        goods.setSpecs(jsonObject.get("specs").toString());
        goods.setThumbnail(jsonObject.get("thumbnail").toString());
        goods.setCreate_time(new Date().getTime());
        goods.setWeight(0.00);
        goods.setHave_spec(1);
        //添加保险方案
        goods.setCentral_subsidies(jsonObject.getDouble("central_subsidies"));
        goods.setProvince_subsidies(jsonObject.getDouble("province_subsidies"));
        goods.setCity_subsidies(jsonObject.getDouble("city_subsidies"));
        goods.setRegion_subsidies(jsonObject.getDouble("region_subsidies"));
        goods.setAvoid_subsidies(jsonObject.getDouble("avoid_subsidies"));
        goods.setOther_subsidies(jsonObject.getDouble("other_subsidies"));
        goods.setFarmer_subsidies(jsonObject.getDouble("farmer_subsidies"));
        goods.setInsured_subsidies(jsonObject.getDouble("insured_subsidies"));
        //添加保险区域
        SysArea sysArea = sysAreaMapper.getByAreaCode(jsonObject.get("province_area_code").toString());
        goods.setProvince_id(sysArea.getProvince_id());
        goods.setProvince(sysArea.getArea_name());
        SysArea sysAreaCigy = sysAreaMapper.getByAreaCode(jsonObject.get("city_area_code").toString());
        goods.setCity_id(sysAreaCigy.getCity_id());
        goods.setCity(sysAreaCigy.getArea_name());
        goods.setArea_code(sysAreaCigy.getArea_code());

        return JsonResultUtil.getErrorJson("更新失败!");
    }

    /**
     * 上传图片
     *
     * @param file
     * @return
     */
    @ResponseBody
    @RequestMapping("upload/inpolicyImage")
    public ImgResponseUtil uploadimg1(@RequestBody MultipartFile file) {
        String fileName = file.getOriginalFilename();
        if (!FileUtil.isAllowUpImg(fileName)) {
            throw new IllegalArgumentException("不被允许的上传文件类型");
        }
        String ext = FileUtil.getFileExt(fileName);
        fileName = DateUtil.toString(new Date(), "mmss") + StringUtil.getRandStr(4) + "." + ext;
        String static_server_path = SystemSetting.getStatic_server_path();
        String filePath = static_server_path + "/attachment/";
        String subFolder = "insuranceLogo";
        if (subFolder != null) {
            filePath += subFolder + "/";
        }
        String path = EopSetting.FILE_STORE_PREFIX + "/attachment/" + (subFolder == null ? "" : subFolder) + "/" + "/" + fileName;
        filePath += fileName;
        try {
            FileUtil.write(file.getInputStream(), filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String insuranceLogo = path;
        ImgResponseUtil imgResponseUtil = new ImgResponseUtil();
        imgResponseUtil.setSuccess(true);
        imgResponseUtil.setResult(insuranceLogo);
        return imgResponseUtil;
    }

    /**
     * 上传图片
     * @param createThumb //是否生成缩略图
     * @param subFolder //文件夹
     * @param ajax 是否为ajax异步提交
     * @param file //文件
     * @param width //图片宽 单位px
     * @param height //图片高度
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/upload")
    public Object upload(int createThumb,String subFolder,Integer ajax,@RequestBody MultipartFile file,Integer width,Integer height) {
        try{
            String path=null;
            if (file != null && file.getOriginalFilename() != null) {

                try{
                    if (subFolder == null) {
                        subFolder = "";
                    }
                    InputStream stream=file.getInputStream();
                    IUploader uploader= UploadFacatory.getUploaer();
                    if (createThumb == 1) {
                        path = uploader.upload(stream, subFolder,file.getOriginalFilename(), width, height)[0];
                    } else {
                        path = uploader.upload(stream, subFolder,file.getOriginalFilename());
                    }
                }catch(IllegalArgumentException e){
                    return JsonResultUtil.getErrorJson(e.getMessage());
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                // 将本地图片路径换为静态资源服务器的地址
                if (path != null)
                    path = StaticResourcesUtil.convertToUrl(path);

                if (ajax == 1) {
                    Map map= new HashMap();
                    map.put("result", 1);
                    map.put("path", path);
                    map.put("thumbnail", StaticResourcesUtil.getThumbPath(path, "_thumbnail"));
                    map.put("filename", file.getOriginalFilename());
                    return map;
                }
            }
        } catch(RuntimeException e) {
            Logger logger = Logger.getLogger(getClass());
            logger.error("上传图片出错:"+e);
        }
        return JsonResultUtil.getErrorJson("请选择文件");
    }
}
